import React,{ useEffect, useState,useRef } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { AtModal } from 'taro-ui';
import { View, Image, Text } from '@tarojs/components'
import {debounce} from '@/utils/helper'
import {filterTel} from '@/utils/index';
import md5 from '@/utils/md5'
import YiCode from '@/components/yi-code'
import "taro-ui/dist/style/components/modal.scss";
import './index.scss'

export default function CardDetail(props) {
  const {router} = Taro.getCurrentInstance()
  const [record,setRecord] = useState({})
  const lock = useRef(false);
  const cutDownTime = useRef(60); //60s
  const [showChangePsw,setShowChangePsw] = useState(false)
  const [showBidding,setShowBidding] = useState(false)
  const [captcha,setCaptcha] = useState('')
  const [captchaBack,setCaptchaBack] = useState('')
  const [getCodeText, setGetCodeText] = useState('获取验证码');
  const [modalTitle,setModalTitle] = useState('修改会员卡密码')
  const [modalSpan,setModalSpan] = useState('为了保证你的账号安全，请输入会员卡预留手机号的短信验证码进行下一步操作。')
  const [messageInfo,setMessageInfo] = useState('')
  useDidShow(()=>{
    Taro.$post(`/cinema-app/api/card/getMyGiftCardInfo`,{
      "id": router.params.id,
      "type": router.params.isDxCard
    }).then(res=>{
      if(res.code == '1'){
        setRecord(res.content)
      }else{
        Taro.$toast(res.message)
      }
    })
  })

    const getCode = debounce(() => {
      if (lock.current) {
        return;
      }
      if (getCodeText != '获取验证码') {
        return;
      }
      if (modalTitle != '修改会员卡密码') {
        return;
      }
      if (!filterTel(record.userPhone)) {
        Taro.showToast({
          title: '请填写正确的手机号',
          icon: 'none',
        });
        return;
      }
      lock.current = true;
      Taro.$post('/notification/codes/auth',{
        recv: record.userPhone,
        verifyValue: '11111',
      }).then(res=>{
        if(res.code == '1'){
          Taro.$toast('发送成功')
          setGetCodeText(`重新获取验证码 (${cutDownTime.current})`);
          let timer = setInterval(function () {
            cutDownTime.current--;
            if (cutDownTime.current <= 0) {
              clearInterval(timer);
              setGetCodeText('获取验证码');
              cutDownTime.current = 60;
              lock.current = false;
              return;
            }
            setGetCodeText(`重新获取验证码 (${cutDownTime.current})`);
          }, 1000);
        }else{
          Taro.$toast(res.message)
        }
      })
    }, 2000);
  return (
    <View className='page-card-detail'>
      <View className="vip-group" style={{background:record.backgroundContent?.includes('http')?`url(${record.backgroundContent})`:record.backgroundContent}}>
        <View className="group-header">
          <Image className='header-img' src={Taro.getStorageSync('appConfig')?.iconUrl || require('@/images/mine/logo.png')} mode='aspectFill'></Image>
          <View className="header-info">
            <View className="info-h2">{record.cardName}</View>
            <View className="info-p">{record.cardNo}</View>
          </View>
        </View>
        <View className="group-footer">
          {record.typeDesc}
          <View><Text style={{fontWeight:400}}>余额：</Text>¥{record.amount}</View>
        </View>
      </View>
      <View className="card-detail">
        {record.cinemaName?
        <View className="card-item">
          <Text className='item-label'>开卡影城</Text>
          <Text className="item-info">{record.cinemaName}</Text>
        </View>:null}
        <View className="card-item">
          <Text className='item-label'>有效期</Text>
          <Text className="item-info">{record.effective}</Text>
        </View>
        <View className="card-item">
          <Text className='item-label'>预留手机号</Text>
          <Text className="item-info">{record.userPhone}</Text>
        </View>
        <View className="card-item">
          <Text className='item-label'>会员卡状态</Text>
          <Text className="item-info">{record.statusDesc}</Text>
        </View>
      </View>
      <View className="card-detail" style={{background:'transparent'}}>
        <View className="card-item">
          {router.params.isDxCard == '1'?null:<Text className='item-button' style={{marginRight:'auto'}} onClick={()=>{getCode();setShowChangePsw(true)}}>修改会员卡密码</Text>}
          <Text className="item-button" onClick={()=>{setShowBidding(true)}}>解绑会员卡</Text>
        </View>
      </View>
      <AtModal className="detail-modal" isOpened={showChangePsw} onClose={()=>{setShowChangePsw(false)}}>
        <View className="modal-header">
          <View className='at-icon at-icon-close' onClick={()=>{setShowChangePsw(false)}}></View>
          <View className="header-h2">{modalTitle}</View>
          <View></View>
        </View>
        {showChangePsw?
        <View className="modal-main">
          <View className="main-span">{modalSpan}</View>
          <View className="main-h2">+86 {record.userPhone}</View>
          <YiCode isFocus inputType={modalTitle == '修改会员卡密码'?'number':'password'} value={captcha} onConfirm={(code) => {
            setCaptcha(code)
          }} />
          {messageInfo?<View className="main-info"><Text style={{marginRight:'4px'}} className='at-icon at-icon-alert-circle'></Text>{messageInfo}</View>:null}
        </View>:null}
        <View className="modal-footer">
          {modalTitle == '修改会员卡密码'?<View className="footer-go" onClick={()=>{
            if(!captcha.trim()) return;
            let data = {
              recv: record.userPhone,
              code: captcha
            }
            Taro.$get(`/notification/codes/V1/${captcha}`,data).then(res=>{
              setCaptcha('')
              if(res.code == '1'){
                setCaptchaBack(data.code)
                setModalTitle('设置新的会员卡密码')
                setModalSpan('短信验证已通过，请设置新的会员卡密码。')
                setMessageInfo('')
              }else{
                setMessageInfo(res.message)
              }
            })
          }}>下一步</View>:<View className="footer-go" onClick={()=>{
            if(!captcha.trim()) return;
            Taro.$post('/cinema-app/api/card/editCardPassword',{
              id: record.id,
              password: md5.hexMD5(captcha),
              mobile:record.userPhone,
              code:captchaBack
            }).then(res=>{
              setCaptcha('')
              if(res.code == '1'){
                Taro.$toast('提交成功')
                setModalTitle('修改会员卡密码')
                setModalSpan('为了保证你的账号安全，请输入会员卡预留手机号的短信验证码进行下一步操作。')
                setMessageInfo('')
                setShowChangePsw(false)
              }else{
                setMessageInfo(res.message)
              }
            })
          }}>确认</View>}
          {modalTitle == '修改会员卡密码'?<View className="footer-get" style={{color:getCodeText.includes('重新获取')?'#96989A':''}} onClick={()=>{getCode()}}>{getCodeText}</View>:null}
        </View>
      </AtModal>
      <AtModal className="detail-modal" isOpened={showBidding} onClose={()=>{setShowBidding(false)}}>
        <View className="modal-header">
          <View className='at-icon at-icon-close' onClick={()=>{setShowBidding(false)}}></View>
          <View className="header-h2">解除会员卡绑定</View>
          <View></View>
        </View>
        {showBidding?
        <View className="modal-main">
          <View className="main-span" style={{marginBottom:'24px'}}>为了保证你的账号安全，请输入您的会员卡密码后进行下一步操作。</View>
          <YiCode isFocus inputType='password' value={captcha} onConfirm={(code) => {
            setCaptcha(code)
          }} />
          {messageInfo?<View className="main-info"><Text style={{marginRight:'4px'}} className='at-icon at-icon-alert-circle'></Text>{messageInfo}</View>:null}
        </View>:null}
        <View className="modal-footer">
          <View className="footer-go" onClick={()=>{
            if(captcha.trim()){
              const data = {
                cardId: record.id,
                password: captcha,
                type:record.isDxCard
              }
              Taro.$post('/cinema-app/api/card/unFineCardTaskBinding',data,'1').then(res=>{
                if(res.code == '1'){
                  Taro.$toast('提交成功')
                  setTimeout(() => {
                    Taro.navigateBack()
                  }, 1000);
                }else{
                  Taro.$toast(res.message || '解绑失败')
                  setCaptcha('')
                }
              })
            }
          }}>确定</View>
        </View>
      </AtModal>
      {record.allowRecharge?
      <View className="card-footer">
        <View className="footer-button" onClick={()=>{
          Taro.navigateTo({
            url:`/mineSubPack/recharge-card/index?id=${record.id}&isDxCard=${record.isDxCard}`
          })
        }}>立即充值</View>
      </View>:null}
    </View>
  )
}